<?php
/*
 * @Author: 杨红兵 
 * @Date: 2022-08-08 11:34:02 
 * @Last Modified by: 杨红兵
 * @Last Modified time: 2022-09-08 11:05:10
 */

namespace app\libraries\utils\queue;

use app\libraries\utils\Util;
use think\queue\Worker as QueueWorker;
use Throwable;

class Worker extends QueueWorker
{
    /**
     * Process a given job from the queue.
     * @param string $connection
     * @param \think\queue\Job    $job
     * @param int    $maxTries
     * @param int    $delay
     * @return void
     */
    public function process($connection, $job, $maxTries = 0, $delay = 0)
    {
        try {
            parent::process($connection, $job, $maxTries, $delay);
        } catch (Throwable $ex) {
            LogError('queue_worker', '任务执行出错', $ex->getMessage(), Util::normalizeException($ex));
        }
    }

    /**
     * 执行下个任务
     * @param string $connection
     * @param string $queue
     * @param int    $delay
     * @param int    $sleep
     * @param int    $maxTries
     * @return bool
     * @throws Exception
     */
    public function runNextJob($connection, $queue, $delay = 0, $sleep = 3, $maxTries = 0): bool
    {
        $job = null;
        try {
            $job = $this->getNextJob($this->queue->connection($connection), $queue);
        } catch (Throwable $ex) {
            LogError('queue_worker', '获取待执行任务出错', $ex->getMessage(), Util::normalizeException($ex));
        }

        if ($job) {
            $this->runJob($job, $connection, $maxTries, $delay);
            return true;
        } else {
            $this->sleep($sleep);
            return false;
        }
    }
}
